package eu.daxiongmao.skills.model;

import eu.daxiongmao.skills.util.constant.EntityFieldSize;
import eu.daxiongmao.skills.util.validation.EmailValidation;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * Application user.
 *
 * @author Guillaume Diaz
 * @version 1.0 - January 2014
 */
@XmlRootElement
@Entity
@Table(name = "users")
public class User implements Serializable {

    /**
     * Object ID in database.
     */
    @XmlElement(required = false)
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @XmlElement(required = false)
    @EmailValidation(message = "not a valid email")
    @Column(name = "email", nullable = true, length = EntityFieldSize.VARCHAR_MEDIUM_TEXT_255, unique = true)
    private String email = null;

    @XmlElement(required = false)
    @Column(name = "first_name", nullable = true, length = EntityFieldSize.VARCHAR_MEDIUM_TEXT_200, unique = false)
    private String firstName = null;

    @XmlElement(required = false)
    @Column(name = "last_name", nullable = true, length = EntityFieldSize.VARCHAR_MEDIUM_TEXT_200, unique = false)
    private String lastName = null;

    @XmlElement(required = true)
    @Size(min = 1, max = EntityFieldSize.VARCHAR_SMALL_SIZE_50)
    @Column(name = "login", nullable = false, length = EntityFieldSize.VARCHAR_SMALL_SIZE_50, unique = true)
    private String login;

    @XmlElement(required = false)
    @Column(name = "password", nullable = false, length = EntityFieldSize.VARCHAR_SMALL_TEXT_75, unique = false)
    private String password;

    /**
     * <p>
     * List of user's group(s).<br/>
     * Each user can belong to one or more groups.
     * </p>
     * <p>
     * This is a join table. <br/>
     * The 'USER_ID' column refers to the USER, while the 'GROUP_ID' column refers to the GROUP.<br/>
     * Note that for the [ @ ManyToMany ] all the mapping is done here.
     * </p>
     */
    @XmlElement(required = false)
    @ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
    @JoinTable(name = "users_groups_join", joinColumns = {
        @JoinColumn(name = "user_id", referencedColumnName = "id")}, inverseJoinColumns = {
        @JoinColumn(name = "group_id", referencedColumnName = "id")})
    private List<UserGroup> groups;

    @Override
    public final boolean equals(final Object target) {
        // Check param
        if (target == null) {
            return false;
        }
        if (getClass() != target.getClass()) {
            return false;
        }

        // Check isActive
        if (!super.equals(target)) {
            return false;
        }

        // Login must be unique
        User other = (User) target;
        return other.getLogin() != null && this.login != null && other.getLogin().equalsIgnoreCase(this.login.trim());
    }

    @Override
    public final int hashCode() {
        int hash = super.hashCode();
        if (this.login != null) {
            hash += this.login.trim().hashCode();
        }
        return hash;
    }

    public String getEmail() {
        return email;
    }

    public List<UserGroup> getGroups() {
        if (this.groups == null) {
            this.groups = new ArrayList<>();
        }
        return this.groups;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getLogin() {
        String target = login;
        if (target != null) {
            target = target.trim();
        }
        return target;
    }

    public String getPassword() {
        return password;
    }

    public void setEmail(final String email) {
        this.email = email;
    }

    public void setFirstName(final String firstName) {
        this.firstName = firstName;
    }

    public final void setGroups(final List<UserGroup> groups) {
        if (groups != null) {
            this.groups = groups;
        }
    }

    public User() {
    }

    public void setLastName(final String lastName) {
        this.lastName = lastName;
    }

    public void setLogin(final String login) {
        this.login = login;
    }

    public void setPassword(final String password) {
        this.password = password;
    }

    public Long getId() {
        return id;
    }

    public void setId(final Long id) {
        this.id = id;
    }

    @Override
    public final String toString() {
        StringBuilder log = new StringBuilder("User # ");
        if (id != null && id > 0) {
            log.append("ID: ").append(id).append(" | ");
        }

        // Extract name
        if (firstName != null) {
            log.append(firstName);
            if (lastName != null) {
                log.append(" ").append(lastName);
            }
            log.append(" | ");
        } else if (lastName != null) {
            log.append(lastName).append(" | ");
        }

        // Optional attributes
        if (email != null) {
            log.append(email).append(" | ");
        }

        // mandatory stuff
        log.append("login: ").append(login);

        return log.toString();
    }
}
